package game.player.pacman;

import game.core.G;
import game.core.Game;
import gui.AbstractPlayer;

public class PacBen extends AbstractPlayer {
	private static enum State {
		ATTACKING, COLLECTING, FLEEING
	};

	private State currentState = State.COLLECTING;
	private int targetGhost = -1;

	private long fleeEnd = 0;

	@Override
	/**
	 * Idea: The initial state for PacBen is COLLECTING, so the PacMan is running
	 * around picking up pills. If he comes to close to a ghost he tries to flee
	 * for a short while, trying to get as much distance to the nearest ghost as possible.
	 * 
	 * ToDo: Attacking. If there is no way to flee, try to get a power pill and attack
	 * the nearest ghost
	 */
	public int getAction(Game game, long timeDue) {
		switch (currentState) {
		case ATTACKING:

			break;
		case COLLECTING:
			// Get the nearest ghost num and his (euclidean) distance to pacman
			double minDistance = 3000;
			int minDistanceGhostNum = -1;

			for (int i = 0; i < Game.NUM_GHOSTS; i++) {
				double dist = Math.abs(game.getEuclideanDistance(
						game.getCurPacManLoc(), game.getCurGhostLoc(i)));
				if (dist < minDistance) {
					minDistanceGhostNum = i;
					minDistance = dist;
				}
			}

			// If the distance is below 30, fleeeeeeeeeee
			if (minDistance < 30 && minDistanceGhostNum >= 0) {
				// Try to flee
				System.out.println(System.currentTimeMillis()
						+ ": Fleeing from ghost " + minDistanceGhostNum
						+ " - Distance: " + minDistance);
				targetGhost = minDistanceGhostNum;
				fleeEnd = timeDue + 2000;
				currentState = State.FLEEING;
			}

			// If not, just collect pills
			int[] activePills = game.getPillIndicesActive();

			return game.getNextPacManDir(game.getTarget(game.getCurPacManLoc(),
					activePills, true, G.DM.PATH), true, Game.DM.PATH);
		case FLEEING:
			// Flee for one second, if this time is over go back to collecting
			if (fleeEnd < timeDue) {
				currentState = State.COLLECTING;
			}

			// Try to get as far away as possible from the ghost
			return game.getNextPacManDir(game.getTarget(game.getCurPacManLoc(),
					new int[] { game.getCurGhostLoc(targetGhost) }, true,
					G.DM.PATH), false, Game.DM.PATH);
		}
		
		// If this is printed, something is wrong
		System.out.println(timeDue);
		return 1;
	}

	@Override
	public String getGroupName() {
		return "PacBen";
	}
}
